package com.reeygu.item.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.reeygu.item.exception.GlobalException;
import com.reeygu.item.mapper.UserMapper;
import com.reeygu.item.pojo.User;
import com.reeygu.item.service.UserService;
import com.reeygu.item.utils.CookieUtil;
import com.reeygu.item.utils.MD5Util;
import com.reeygu.item.utils.UUIDUtil;
import com.reeygu.item.vo.LoginVo;
import com.reeygu.item.vo.RespBean;
import com.reeygu.item.vo.RespBeanEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
* @author a1304
* @description 针对表【t_user】的数据库操作Service实现
* @createDate 2023-08-03 22:35:41
*/
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public RespBean doLogin(LoginVo loginVo, HttpServletRequest request, HttpServletResponse response) {
        String phone = loginVo.getMobile();
        String pass = loginVo.getPassword();
        //通过手机号查询数据库校验密码
        User user = userMapper.selectById(loginVo.getMobile());
        if(user == null){
            //用户不存在
            throw new GlobalException(RespBeanEnum.PHONE_ERROR);
        }
        //匹配密码
        if(!MD5Util.getPassFromUpdatePass(pass, user.getSlat()).equals(user.getPassword())){
            log.warn("用户:" + phone + " 在 " + new Date() + " 时刻输入错误密码");
            throw new GlobalException(RespBeanEnum.PASS_ERROR);
        }
        String ticket = UUIDUtil.uuid();
        request.getSession().setAttribute(ticket, user);
        //上面SpringSession的形式可以转换成下面redis存储的形式
//        redisTemplate.opsForValue().set("userTicket:" + ticket, user, 3600L, TimeUnit.SECONDS);
        redisTemplate.opsForValue().set("userTicket:" + ticket, user);
        CookieUtil.setCookie(request, response, "userTicket", ticket);
        log.info("用户:" + phone + " 在 " + new Date() + " 时刻成功登录,userTicket:" + ticket);
        return RespBean.success(ticket);
    }

    @Override
    public User getUserInfo(String ticket, HttpServletRequest request, HttpServletResponse response) {
        User user = (User) redisTemplate.opsForValue().get("userTicket:" + ticket);
        //再刷新一遍用户cookie数据，保持时效
        if(user != null) {
            CookieUtil.setCookie(request, response, "userTicket", ticket);
//            redisTemplate.opsForValue().set("userTicket:" + ticket, user, 3600L, TimeUnit.SECONDS);
            redisTemplate.opsForValue().set("userTicket:" + ticket, user);
        }
        return user;
    }
}
